package com.hzit.gate.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.ruoyi.common.core.domain.R;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsConfigurationSource;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.pattern.PathPatternParser;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Configuration
public class GatewayConfig {

	@Bean
	public CorsWebFilter webFilter(){
		UrlBasedCorsConfigurationSource config = new UrlBasedCorsConfigurationSource() ;
		CorsConfiguration sourceConfig = new CorsConfiguration();
		sourceConfig.setAllowCredentials(true);
		sourceConfig.addAllowedOrigin("*");
		sourceConfig.addAllowedMethod("*");
		sourceConfig.addAllowedHeader("*");
		config.registerCorsConfiguration("/**",sourceConfig);
		return new CorsWebFilter(config);
	}

	/**
	 * 定制网关限流异常信息
	 */
	@PostConstruct
	public void init(){
		GatewayCallbackManager.setBlockHandler(new BlockRequestHandler() {
			@Override
			public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable t) {
				R<HttpStatus> fail = R.fail(HttpStatus.NOT_FOUND.value(), "网关限流异常！");
				return ServerResponse.status(HttpStatus.OK)
						.contentType(MediaType.APPLICATION_JSON)
						.body(BodyInserters.fromObject(fail));
			}
		});
	}
}
